<template>
  <div class="page-container">
    <h1 class="page-title">🎵 音乐库</h1>
    
    <!-- 加载状态 -->
    <div class="loading" v-if="loading">
      <div class="loading-spinner"></div>
    </div>
    
    <!-- 空状态 -->
    <div class="empty-state" v-else-if="musicList.length === 0">
      <img src="/images/empty-music.png" alt="无音乐">
      <p>还没有保存的音乐</p>
      <p style="font-size: 14px;">在散步时生成的音乐可以保存到这里</p>
    </div>
    
    <!-- 音乐列表 -->
    <div class="music-list" v-else>
      <div class="music-item" v-for="music in musicList" :key="music.id">
        <div class="music-cover">
          <img src="/images/music.png" alt="音乐">
        </div>
        <div class="music-info">
          <h4>{{ music.metadata?.poi_name || '散步音乐' }}</h4>
          <p>{{ formatDate(music.created_at) }} · {{ formatDuration(music.duration) }}</p>
          <p v-if="music.metadata?.weather">{{ music.metadata.weather }}</p>
        </div>
        <div class="music-actions">
          <button @click="togglePlay(music)" :title="currentPlayingId === music.id ? '暂停' : '播放'">
            <img :src="currentPlayingId === music.id ? '/images/pause.png' : '/images/play.png'" alt="播放">
          </button>
          <button @click="shareMusic(music)" title="分享">
            <img src="/images/share.png" alt="分享">
          </button>
          <button @click="deleteMusic(music)" title="删除" class="delete-btn">
            <img src="/images/delete.png" alt="删除">
          </button>
        </div>
      </div>
    </div>
    
    <!-- 音频播放器 -->
    <audio ref="audioPlayer" @ended="onAudioEnded"></audio>
  </div>
</template>

<script>
import { musicApi } from '../utils/api'

export default {
  name: 'MusicLibrary',
  data() {
    return {
      loading: false,
      musicList: [],
      currentPlayingId: null
    }
  },
  mounted() {
    this.loadMusicList()
  },
  methods: {
    async loadMusicList() {
      this.loading = true
      
      try {
        const response = await musicApi.getLibrary()
        this.musicList = response.data || response.music || []
      } catch (error) {
        console.error('加载音乐列表失败:', error)
        this.musicList = []
      } finally {
        this.loading = false
      }
    },
    
    togglePlay(music) {
      const audio = this.$refs.audioPlayer
      
      if (this.currentPlayingId === music.id) {
        // 暂停当前播放
        audio.pause()
        this.currentPlayingId = null
      } else {
        // 播放新音乐
        audio.src = music.file_url
        audio.play()
        this.currentPlayingId = music.id
      }
    },
    
    onAudioEnded() {
      this.currentPlayingId = null
    },
    
    shareMusic(music) {
      if (navigator.share) {
        navigator.share({
          title: music.metadata?.poi_name || '散步音乐',
          text: '来自步语的散步音乐',
          url: music.file_url
        })
      } else {
        // 复制链接
        navigator.clipboard.writeText(music.file_url)
        alert('链接已复制到剪贴板')
      }
    },
    
    async deleteMusic(music) {
      if (!confirm(`确定要删除"${music.metadata?.poi_name || '散步音乐'}"吗？`)) {
        return
      }
      
      try {
        await musicApi.delete(music.id)
        this.musicList = this.musicList.filter(m => m.id !== music.id)
        
        if (this.currentPlayingId === music.id) {
          this.$refs.audioPlayer.pause()
          this.currentPlayingId = null
        }
      } catch (error) {
        console.error('删除音乐失败:', error)
        alert('删除失败，请重试')
      }
    },
    
    formatDate(dateStr) {
      if (!dateStr) return ''
      const date = new Date(dateStr)
      return `${date.getMonth() + 1}月${date.getDate()}日`
    },
    
    formatDuration(seconds) {
      if (!seconds) return ''
      const mins = Math.floor(seconds / 60)
      const secs = seconds % 60
      return `${mins}:${secs.toString().padStart(2, '0')}`
    }
  }
}
</script>

<style scoped>
.delete-btn:hover {
  background: #ffebee !important;
}

.delete-btn:hover img {
  filter: brightness(0) saturate(100%) invert(27%) sepia(94%) saturate(2255%) hue-rotate(346deg) brightness(89%) contrast(97%);
}
</style>
